<template>
	<view>
     <!-- 自定义导航栏 -->
        <u-navbar :border-bottom="false"  background-color="red" >
            <view slot="left" class="u-nav-slot" @click="goBack">
          
            </view>
        </u-navbar>
		<view class="top">

			<view class="tab">
				<view class="tab-item" :class="{active:!isReg}" @tap="isReg=false">
					登录 
				</view>
				<view class="tab-item" :class="{active:isReg}" @tap="isReg=true">
					注册
				</view>
			</view>
		</view>
		<view class="content">
			<view class="from">
				<view  class="form-item" :class="userRes.status">
					<label for="" class="item-title iconfont icon-userfill" />
					<view class="item-content">
						<input class="" type="text" v-model="userName" @blur="checkUserName" placeholder="请输入用户名" />
					</view>
					<view class="tip">
						{{userRes.msg}}
					</view>
				</view>
                <view  class="form-item" :class="passwordRes.status">
                	<label for="" class="item-title iconfont icon-password" />
                	<view class="item-content">
                		<input class="" type="password" v-model="password" @blur="checkPassword" placeholder="请输入密码" />
                	</view>
                	<view class="tip">
                		{{passwordRes.msg}}
                	</view>
                </view>
				<!-- <view class="form-item" :class="phoneRes.status">
					<label class="item-title iconfont icon-dianhuafill" />
					<view class="item-content">
						<input type="number" confirm-type="next" maxlength="11" v-model="phone" @blur='checkPhone'
							placeholder="请输入常用手机号" />
					</view>
					<view class="tip">
						{{phoneRes.msg}}
					</view>
				</view> -->
                <view class="form-item" :class="confirmPasswordRes.status"  v-if="isReg">
                    <label for="" class="item-title iconfont icon-password" />
                    <view class="item-content">
                        <input class="" type="password" v-model="confirmPassword" @blur="checkConfirmPassword" placeholder="请输入确认密码" />
                    </view>
                    <view class="tip">
                        {{ confirmPasswordRes.msg }}
                    </view>
                </view>
				<view class="form-item " :class="imgRes.status">
					<label class="item-title cuIcon-qrcode" />
					<view class="item-content u-flex">
						<input type="text" confirm-type="send" maxlength="4" v-model="imgCode" @blur='checkImg'
							placeholder="请输入图形码" @confirm="sendCode" />
						<view @tap="getImgCode" class="img-code"
							:style="{backgroundImage: `url(data:image/png;base64,${imageBase64})`}"></view>
					</view>
					<view class="tip">
						{{imgRes.msg}}
					</view>
				</view>
		
				<view class="form-footer">
					<view type="default" class="submit" @tap="loginP" v-show="!isReg">登录</view>
					<view type="default" class="submit" @tap="registerP" v-show="isReg">注册</view>
					<!--					<view class="forgot">忘记密码?</view>-->
				</view>
			</view>
			<view :class="{shake:shake}" class="agreement u-flex" @tap="agree=!agree" v-if="!isReg">
				<checkbox :class="{checked:agree}" class="round" style="transform: scale(0.7);" :checked="agree">
				</checkbox>
				登录即表明同意
				<navigator url="/pages/agreement/agreement?id=shiyong" class="text-blue" @tap.stop>《用户使用协议》
				</navigator>
				和
				<navigator url="/pages/agreement/agreement?id=yinsixieyi" class="text-blue" @tap.stop>《隐私条款》
				</navigator>
			</view>
			<view class="bottom">
                
				<!-- #ifdef APP-PLUS
				<view class="bottom-title" v-show="!examine">
					<text class="text-gray">更多登录方式</text>
				</view>
				<view class="bottom-content" v-show="!examine">
					
					<view class="mode" @tap="wxLogin">
						<view class="cu-avatar round lg wx">
							<text class="iconfont icon-weixin"></text>
						</view>
						<text class="label text-gray">微信</text>
					</view>
				</view>
				#endif -->
				
			</view>
		</view>
	</view>

</template>

<script>
	import {
		isValidPhone
	} from '@/utils/check.js'
	import {
		toast,
		delay,
		goback
	} from '@/utils/util.js'
	import * as userAPI from '@/api/user.js'
	import {
		mapActions,
		mapGetters
	} from 'vuex'
	let weixinAuthService
	export default {
		data() {
			return {
				isReg: false,
				userName: '',
                password:'',
                confirmPassword:'',
				userRes: {
					status: '',
					msg: '请输入用户名'
				},
                passwordRes:{
                   status: '',
                   msg: '请输入密码'
                },
                confirmPasswordRes:{
                    status: '',
                    msg: '请输入确认密码'
                },
                
				verifyCode: '',
				verifyRes: {
					status: '',
					msg: '请输入验证码'
				},
				phone: '',
				phoneRes: {
					status: '',
					msg: '请输入电话号码',
				},
				imgCode: '',
				imgRes: {
					status: '',
					msg: '请输入图形码'
				},
				timer: 0,
				imageBase64: '',
				imgToken: '',
				agree: false,
				shake: false,
                 DEFAULT_AVATAR :'https://mixin-1362694037.cos.accelerate.myqcloud.com/mixin/default_head.png'
			}
		},
		computed: {
			examine(){
				return false
			},
			canLogin() {
				return this.phoneRes.status === 'success' && this.verifyRes.status === 'success'
			},
			canReg() {
				return this.phoneRes.status === 'success' && this.userRes.status === 'success' && this.verifyRes.status ===
					'success'
			},
			verCodeText() {
				if (!this.timer) {
					return '获取验证码'
				}
				return `${this.timer}秒`
			}
		},
		onLoad() {
			this.getImgCode();
			// // #ifdef APP-PLUS
			// plus.oauth.getServices((services) => {
			// 	weixinAuthService = services.find((service) => {
			// 		return service.id === 'weixin'
			// 	})
			// });
			// // #endif
		},
		methods: {
            
            
               goBack() {
                        uni.navigateBack(); // 返回上一页
                    },
			...mapActions('user', ['login']),
			async wxLogin() {
				try {
					await this.checkAgree();
				} catch (e) {
					return
				}
				try {
					uni.showLoading({
						title: '正在登陆中'
					});
					const {
						code
					} = await new Promise((resolve, reject) => {
						weixinAuthService.authorize(resolve, reject)
					})
					console.log('授权完成', code)
					const {
						token,
						userInfo
					} = await userAPI.wxAppLogin(code)
					console.log('请求完成', token)
					await this.login({
						token,
						userInfo
					})
					console.log('仓库完成')
					uni.showToast({
						title: '登录成功',
						duration: 1000
					});
					await delay(1000)
					goback()
				} catch (e) {
					console.log(e)
					toast('登录失败')
					await delay(1000)
				} finally {
					uni.hideLoading()
				}
			},
            checkConfirmPassword() {
                    if (this.confirmPassword === '') {
                        this.confirmPasswordRes = { status: 'error', msg: '请输入确认密码' };
                        return Promise.reject('请输入确认密码');
                    } else if (this.confirmPassword !== this.password) {
                        this.confirmPasswordRes = { status: 'error', msg: '两次密码不一致' };
                        return Promise.reject('两次密码不一致');
                    } else {
                        this.confirmPasswordRes = { status: 'success', msg: '' };
                        return Promise.resolve();
                    }
                },
            
            
			async qqLogin() {
				toast('小哥哥正在努力开发中', 2000)
			},
			async checkAgree() {
				if (!this.agree) {
					// #ifdef APP-PLUS
					uni.vibrateShort()
					// #endif
					this.shake = true
					delay(500).then(() => {
						this.shake = false
					})
					throw toast('请勾选同意协议')
				}
			},
			// async checkUserName() {
			// 	if (!this.userName) {
			// 		this.userRes.status = 'error';
			// 		this.userRes.msg = '请输入用户名'
			// 		throw new Error('请输入用户名')
			// 	} else {
			// 		this.userRes.status = 'success'
			// 		return true;
			// 	}
			// },
            
checkUserName() {
    const username = this.userName.trim();

    if (!username) {
        this.userRes = { status: 'error', msg: '用户名不能为空' };
        return Promise.reject('用户名不能为空');
    }

    // 正则：必须是英文、数字，不允许汉字，长度6~15
    const usernameRegex = /^[a-zA-Z0-9]{6,15}$/;

    if (!usernameRegex.test(username)) {
        this.userRes = { status: 'error', msg: '用户名需为6-15位英文或数字组合，不允许汉字' };
        return Promise.reject('用户名格式不正确');
    }

    if (/[\u4e00-\u9fa5]/.test(username)) {
        this.userRes = { status: 'error', msg: '用户名不能包含汉字' };
        return Promise.reject('用户名不能包含汉字');
    }

    // 新增判断：不能是纯数字
    if (/^\d+$/.test(username)) {
        this.userRes = { status: 'error', msg: '用户名不能为纯数字' };
        return Promise.reject('用户名不能为纯数字');
    }

    this.userRes = { status: 'success', msg: '' };
    return Promise.resolve();
},
checkPassword() {
    const password = this.password.trim();

    if (!password) {
        this.passwordRes = { status: 'error', msg: '密码不能为空' };
        return Promise.reject('密码不能为空');
    }

    if (password.length < 6) {
        this.passwordRes = { status: 'error', msg: '密码长度需大于等于6位' };
        return Promise.reject('密码长度不足');
    }

    // 确保密码不包含汉字
    if (/[\u4e00-\u9fa5]/.test(password)) {
        this.passwordRes = { status: 'error', msg: '密码不能包含汉字' };
        return Promise.reject('密码不能包含汉字');
    }

    this.passwordRes = { status: 'success', msg: '' };
    return Promise.resolve();
},
			async checkPhone() {
				if (!this.phone) {
					this.phoneRes.status = 'error';
					this.phoneRes.msg = '请输入电话号码'
					throw new Error('请输入电话号码')
				} else if (!isValidPhone(this.phone)) {
					this.phoneRes.status = 'error';
					this.phoneRes.msg = '电话号码格式错误'
					throw new Error('电话号码格式错误')
				} else {
					this.phoneRes.status = 'success'
					return true;
				}

			},
			async checkVerify() {
				if (!this.verifyCode) {
					this.verifyRes.status = 'error';
					this.verifyRes.msg = '请输入验证码'
					throw new Error('请输入验证码')
				} else {
					this.verifyRes.status = 'success'
					return true;
				}
			},
			async checkImg() {
				if (!this.imgCode) {
					this.imgRes.status = 'error';
					this.imgRes.msg = '请输入图形码'
					throw new Error('请输入图形码')
				} else {
					this.imgRes.status = 'success'
					return true;
				}
			},
            
            improveAvatar(token){
            	return new Promise((resolve,reject)=>{
            		uni.navigateTo({
            			url:`/pages/improve/avatar?token=${token}`,
            			events:{
            				successful:resolve
            			},
            			fail:reject,
            			success(){
            				
            			}
            		})
            	})
            },
            async loginP() {
                try {
                    await this.checkAgree();  // 检查是否同意协议
                    await Promise.all([this.checkUserName(), this.checkPassword(), this.checkImg()]);
                } catch (e) {
                    return;
                }
            
                if (this.loginP.lock) {
                    uni.showToast({ title: '正在登录中，请勿重复点击' });
                    return;
                }
            
                try {
                    this.loginP.lock = true;
                    // uni.showLoading({ title: '登录中...' });
            
                    const {
                        token,
                        userInfo,
                        setPwd
                    } = await userAPI.realLoginByUserNum({
                        userNum: this.userName,
                        pwd: this.password,
                        verCode: this.imgCode,     // 假设验证码字段是 imgCode
                        verToken: this.imgToken    // 图形验证码 Token
                    });
                    
       
                    if(/default_head.png$/.test(userInfo.avatarUrl)){
                    	const {userName,avatarUrl} = await this.improveAvatar(token)
                    	console.log(userName,avatarUrl)
                    	userInfo.avatarUrl = avatarUrl
                    	userInfo.userName = userName
                    	await delay(500)
                    }
                   
                               // 如果不是默认头像，继续登录流程
                            await this.login({ token, userInfo });
                    uni.showToast({
                    	title: '登录成功',
                    	duration: 1000
                    });
                    await delay(1000)
                    goback(2)
                  
                    
                     
    
                } catch (e) {
                    console.error(e);
                    uni.showToast({ title:e.retDesc, icon: 'none' });
                } finally {
                    uni.hideLoading();
                    this.loginP.lock = false;
                }
            },
			// async loginP() {
			// 	try {
			// 		await this.checkAgree()
			// 		await Promise.all([this.checkPhone(), this.checkVerify()])
			// 	} catch (e) {
			// 		return
			// 	}
			// 	if (this.loginP.lock) {
			// 		throw new Error('正在登陆中,请勿重复点击')
			// 	}
			// 	try {
			// 		this.loginP.lock = true
			// 		uni.showLoading({
			// 			title: '正在登陆中'
			// 		})
			// 		const {
			// 			token,
			// 			userInfo
			// 		} = await userAPI.loginOrRegister({
			// 			mobile: this.phone,
			// 			verCode: this.verifyCode
			// 		})
			// 		await this.login({
			// 			token,
			// 			userInfo
			// 		})
			// 		uni.showToast({
			// 			title: '登录成功',
			// 			duration: 1000
			// 		});
			// 		await delay(1000)
			// 		uni.switchTab({
			// 			url:'/pages/chat/list'
			// 		})
			// 	} catch (e) {
			// 		console.error(e)
			// 		toast('登录失败')
			// 		await delay(1000)
			// 	} finally {
			// 		uni.hideLoading()
			// 		this.loginP.lock = false
			// 	}
			// },
			// async registerP() {
			// 	// await Promise.all([this.checkUserName(), this.checkPhone(), this.checkVerify()])
			// 	const {
			// 		token,
			// 		userInfo
			// 	} = await userAPI.zhuce({
			// 		mobile: this.phone,
			// 		verCode: this.verifyCode,
			// 		invite: ''
			// 	})
			// 	await this.login({
			// 		token,
			// 		userInfo
			// 	})
			// 	uni.showToast({
			// 		title: '注册成功',
			// 		duration: 2000
			// 	});
			// 	await delay(2000)
			// 	uni.navigateBack()
			// },
            async registerP() {
                console.log(2)
                try {
                    // 校验用户名、手机号、验证码、图形码
                    await Promise.all([
                        this.checkUserName(), 
                    
                        this.checkPassword(), 
               this.checkConfirmPassword(), // 新增的确认密码校验
                        this.checkImg()
                    ]);
                } catch (e) {
                    return; // 校验失败直接返回
                }
            
                if (this.registerP.lock) {
                    uni.showToast({ title: '正在注册中，请勿重复点击' });
                    return;
                }
            
                try {
                    this.registerP.lock = true;
                    uni.showLoading({ title: '注册中...' });
            
                    // 调用注册接口
                    const { token, userInfo } = await userAPI.zhuce({
                        userNum: this.userName,     // 用户名
                        pwd: this.password,         // 密码
                        verCode: this.verifyCode,   // 验证码
                        verToken: this.imgToken     // 图形码 Token
                    });
            
                    // 登录成功处理
                    await this.login({ token, userInfo });
                    uni.showToast({ title: '注册成功', duration: 2000 });
                    await delay(2000);
                this.isReg = false; // 切换到登录页签
                    // uni.navigateBack(); // 返回上一页
                } catch (e) {
                    console.error(e);
                    uni.showToast({ title: e.retDesc, icon: 'none' });
                } finally {
                    uni.hideLoading();
                    this.registerP.lock = false;
                }
            },
			async getImgCode() {
				const {
					imageBase64,
					token
				} = await userAPI.getImageCode();
				this.imageBase64 = imageBase64
				this.imgToken = token;

			},
			async sendCode() {
				if (this.timer !== 0) {
					return toast('点击太快,稍后再试');
				}
				await Promise.all([this.checkPhone(), this.checkImg()]);
				try {
					const res = await userAPI.sendMobileCode({
						mobile: this.phone,
						imageToken: this.imgToken,
						imageCode: this.imgCode
					});
					if (!res.status) {
						return toast(res.message)
					}
					this.timer = parseInt(res.time, 0);
					const t = setInterval(() => {
						if (this.timer <= 0) {
							clearInterval(t)
							return;
						}
						this.timer--;
					}, 1000);
				} catch (e) {
					this.getImgCode();
					this.imgCode = ''
				}

			}
		}

	}
</script>
<style>
	page{
		background-color: #FFFFFF;
	}
</style>
<style lang="scss" scoped>
	@keyframes shake {

		0%,
		100% {
			transform: translateX(0)
		}

		10% {
			transform: translateX(-9px)
		}

		20% {
			transform: translateX(8px)
		}

		30% {
			transform: translateX(-7px)
		}

		40% {
			transform: translateX(6px)
		}

		50% {
			transform: translateX(-5px)
		}

		60% {
			transform: translateX(4px)
		}

		70% {
			transform: translateX(-3px)
		}

		80% {
			transform: translateX(2px)
		}

		90% {
			transform: translateX(-1px)
		}
	}

	.img-code {
		min-width: 140rpx;
		height: 70rpx;
		background-size: auto 100%;
		background-repeat: no-repeat;
	}

	.top {
		width: 750rpx;
		height: 360rpx;
		background-image: url("/static/images/background.png");
		background-repeat: no-repeat;
		background-size: cover;
		position: relative;

		.back {
			position: absolute;
			top: 0;
			font-size: 50rpx;
			padding: 10rpx;
			color: #FFFFFF;
			text-shadow: 0 0 5rpx rgba(0, 0, 0, .9);
		}

		.tab {
			position: absolute;
			bottom: 0;
			left: 50%;
			transform: translateX(-50%);
			background-color: #FFFFFF;
			width: 90%;
			padding: 20rpx 40rpx;
			border-radius: 20rpx 20rpx 0 0;

			.tab-item {
				display: inline-block;
				font-size: 36rpx;
				color: #000000;
				margin-right: 40rpx;
				padding: 15rpx 0;
				border-bottom: 10rpx solid transparent;

				&.active {
					border-bottom: 10rpx solid $theme-color;
				}
			}
		}
	}

	.content {
		border-top-left-radius: 40rpx;
		border-top-right-radius: 40rpx;
		display: flex;
		flex-direction: column;
		justify-content: space-between;
		align-items: center;
		min-height: calc(100vh - 360rpx);
	}

	.bottom {
		// padding-bottom: 60rpx;

		.bottom-title {
			display: flex;
			justify-content: center;
			align-items: center;
			background-color: #FFFFFF;
			width: 100%;

			&::before {
				content: "";
				display: block;
				background-color: #aaaaaa;
				height: 1rpx;
				flex: 1;
				margin-right: 10rpx;
			}

			&::after {
				content: "";
				display: block;
				background-color: #aaaaaa;
				height: 1rpx;
				flex: 1;
				margin-left: 10rpx;
			}
		}

		.bottom-content {
			display: flex;
			justify-content: space-around;
			margin: 10rpx 0 20rpx;

			.mode {
				display: flex;
				flex-direction: column;
				align-items: center;

				.label {
					margin-top: 10rpx;
				}

				.wx {
					background-color: #7EBE70;
				}

				.qq {
					background-color: #52B7E1;
				}
			}
		}

		.shake {
			animation: shake .5s ease-out;
			animation-fill-mode: both;
		}
	}

	.from {
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		width: 100%;

		.form-item {
			position: relative;
			margin: 25rpx 0;
			width: 80%;
			font-size: 36rpx;
			line-height: 1.5em;

			&::after {
				font-family: "iconfont" !important;
				position: absolute;
				right: .5em;
				top: 20rpx;
				display: none;
			}

			.tip {
				padding-left: 50rpx;
				padding-top: 10rpx;
				font-size: .8em;
				display: none;
				color: #101010;
			}

			&.success {
				&::after {
					content: "\e8c5";
					color: #09c518;
					display: block;
				}

				.tip {
					display: none;
				}
			}

			&.error {
				.tip {
					color: #F02B2B;
					display: block;
				}

				&::after {
					content: "\e8cb";
					color: #F02B2B;
					display: block;
				}
			}

			.item-title {
				position: absolute;
				left: 20rpx;
				top: 20rpx;
				color: $theme-color;
				font-size: 1.2em;
			}

			.item-content {
				
				border-radius: 100rpx;
				background-color: rgba(245, 246, 247, 1);
				padding: 0 70rpx;

				input {
					width: 100%;
					height: 100%;
					padding: 28rpx 0;
					vertical-align: middle;
				}

				.verify {
					display: inline-block;
					width: 65%;

				}

				.sendCode {
					display: inline-block;
					font-size: 30rpx;
					text-align: center;
					width: 35%;
					color: #CCCCCC;
				}
			}

		}

		.form-footer {
			display: flex;
			flex-direction: column;
			align-items: center;
			width: 80%;
			margin-top: 20rpx;

			.submit {
				width: 100%;
				text-align: center;
				background-color: $theme-color;
				background-image: linear-gradient(249deg, $theme-color 16%, #fbc02d 99%);
				border-radius: 1000rpx;
				padding: 30rpx 0;
				color: #000000;
                font-size: 17px;
			}

			.forgot {
				margin-top: 20rpx;
				color: #FCA326;
				padding: 10rpx 0;
				border-bottom: 2rpx solid #FCA326;
			}
		}

	}
</style>
